package com.loeng.framework.websocket.config;

import com.loeng.framework.websocket.core.handler.JsonWebSocketMessageHandler;
import com.loeng.framework.websocket.core.listener.WebSocketMessageListener;
import com.loeng.framework.websocket.core.security.LoginUserHandshakeInterceptor;
import com.loeng.framework.websocket.core.security.WebSocketAuthorizeRequestsCustomizer;
import com.loeng.framework.websocket.core.session.WebSocketSessionHandlerDecorator;
import com.loeng.framework.websocket.core.session.WebSocketSessionManager;
import com.loeng.framework.websocket.core.session.WebSocketSessionManagerImpl;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.List;

/**
 * WebSocket 自动配置
 *
 * @ ConditionalOnProperty : 允许使用 loeng.websocket.enable=false 禁用 websocket
 *
 * @author loeng zhuo
 */
@AutoConfiguration
@EnableWebSocket
@EnableConfigurationProperties(WebSocketProperties.class)
@ConditionalOnProperty(prefix = "loeng.websocket", name = "enable", matchIfMissing = true)
public class LoengWebSocketAutoConfiguration {

    /**
     * 创建 WebSocketConfigurer 对象，用于注册 WebSocket 的处理器
     *
     * @param handshakeInterceptors       握手拦截器
     * @param webSocketHandler            WebSocket 处理器
     * @param webSocketProperties         WebSocket 配置属性
     * @return WebSocketConfigurer 对象
     */
    @Bean
    public WebSocketConfigurer webSocketConfigurer(HandshakeInterceptor[] handshakeInterceptors,
                                                   WebSocketHandler webSocketHandler,
                                                   WebSocketProperties webSocketProperties) {
        return registry -> registry
                // 添加 WebSocketHandler
                .addHandler(webSocketHandler, webSocketProperties.getPath())
                .addInterceptors(handshakeInterceptors)
                // 允许跨域，否则前端连接会直接断开
                .setAllowedOriginPatterns("*");
    }

    /**
     * 创建自定义 HandshakeInterceptor 对象，用于拦截 WebSocket 的握手请求
     *  主要实现用户认证
     * @return HandshakeInterceptor 对象
     */
    @Bean
    public HandshakeInterceptor handshakeInterceptor() {
        return new LoginUserHandshakeInterceptor();
    }

    /**
     * 创建自定义 WebSocketHandler 对象，用于处理 WebSocket 的消息
     * @param sessionManager              WebSocketSessionManager 对象，用于管理 WebSocketSession
     * @param messageListeners            WebSocketMessageListener 对象列表，用于处理 WebSocket 的消息
     *                                    (实现了该接口的bean 都会收集到集合里 统一收集注入)
     * @return WebSocketHandler 对象
     */
    @Bean
    public WebSocketHandler webSocketHandler(WebSocketSessionManager sessionManager,
                                             List<? extends WebSocketMessageListener<?>> messageListeners) {
        // 1. 创建 JsonWebSocketMessageHandler 对象，处理消息
        JsonWebSocketMessageHandler messageHandler = new JsonWebSocketMessageHandler(messageListeners);
        // 2. 创建 WebSocketSessionHandlerDecorator 对象，处理连接
        return new WebSocketSessionHandlerDecorator(messageHandler, sessionManager);
    }

    /**
     * 创建 WebSocketSessionManager 对象，用于管理 WebSocketSession
     * @return WebSocketSessionManager 对象
     */
    @Bean
    public WebSocketSessionManager webSocketSessionManager() {
        return new WebSocketSessionManagerImpl();
    }

    /**
     * 创建 WebSocketAuthorizeRequestsCustomizer 对象，用于配置 WebSocket 的权限认证
     * @param webSocketProperties         WebSocket 配置属性
     * @return WebSocketAuthorizeRequestsCustomizer 对象
     */
    @Bean
    public WebSocketAuthorizeRequestsCustomizer webSocketAuthorizeRequestsCustomizer(WebSocketProperties webSocketProperties) {
        return new WebSocketAuthorizeRequestsCustomizer(webSocketProperties);
    }

}
